scipy.spatial
scipy.spatial can compute triangulations, Voronoi diagrams, and convex hulls of a set of points, by leveraging the Qhull
library.
Moreover, it contains KDTree
implementations for nearest-neighbor point queries, and utilities for distance computations in various metrics.
In [1]:
%matplotlib inline
import numpy as np
from scipy.spatial import Delaunay, ConvexHull, Voronoi
import matplotlib.pyplot as plt
points = np.random.rand(30, 2) # 30 random points in 2-D
tri = Delaunay(points)
hull = ConvexHull(points)
voronoi = Voronoi(points)
In [2]:
print "Neighbour triangles\n",tri.neighbors[0:5]
print "Simplices\n", tri.simplices[0:5]
print "Points\n", points[tri.simplices[0:5]]
In [3]:
from scipy.spatial import delaunay_plot_2d
delaunay_plot_2d(tri)
pass
In [4]:
from scipy.spatial import convex_hull_plot_2d
convex_hull_plot_2d(hull)
pass
In [5]:
from scipy.spatial import voronoi_plot_2d
voronoi_plot_2d(voronoi)
pass
In [6]:
from scipy.spatial import KDTree, cKDTree
In [7]:
tree = cKDTree(points)
print tree.data
In [8]:
%%timeit
tree.query((0.5,0.5))
In [9]:
test_points = np.random.rand(1000, 2) # 1000 random points in 2-D
In [10]:
%%timeit
tree.query(test_points)
In [11]:
more_points = np.random.rand(10000, 2) # 1000 random points in 2-D
big_tree = KDTree(more_points)
In [12]:
%%timeit
KDTree(more_points)
In [13]:
%%timeit
big_tree.query(test_points)
In [14]:
# Brute force version
def brute_force_distance(pts, spt):
d = pts - spt
d2 = d**2
distances2 = np.einsum('ij->i',d2)
nearest = np.argsort(distances2)[0]
return np.sqrt(distances2[nearest]), nearest
# print np.einsum('ij->i',distances2)
In [15]:
print brute_force_distance(more_points, (0.0,0.0))
print big_tree.query((0.0,0.0))
In [16]:
%%timeit
brute_force_distance(points, (0.5,0.5))
brute_force_distance(points, (0.0,0.0))
brute_force_distance(points, (0.25,0.25))
In [17]:
%%timeit
tree.query(np.array([(0.5,0.5), (0.0,0.0), (0.25,0.25)]))
In [18]:
%%timeit
brute_force_distance(more_points, (0.5,0.5))
# brute_force_distance(more_points, (0.0,0.0))
# brute_force_distance(more_points, (0.25,0.25))
In [19]:
%%timeit
big_tree.query(np.array([(0.5,0.5), (0.0,0.0), (0.25,0.25)]))
In [ ]:
In [ ]: